package models

import (
	"github.com/astaxie/beego"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"log"
	"strings"
)

var session *mgo.Session
var err error
var host = beego.AppConfig.String("host")
var dbName = beego.AppConfig.String("dbname")

//打开数据库链接
func open(tableName string) *mgo.Collection {
	defer exption()
	session, err = mgo.Dial(host)
	if err != nil {
		panic("数据库链接错误！" + err.Error())
	}
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	var c *mgo.Collection
	c = session.DB(dbName).C(tableName)
	return c
}

//关闭数据库链接
func close() {
	if session != nil {
		session.Close()
	}
}

//记录异常
func exption() {
	msg := recover()
	if msg != nil {
		log.Println(msg)
	}
}

func NewObjId() string {
	oid := bson.NewObjectId().String()
	s := strings.Replace(oid, "ObjectIdHex(\"", "", -1)
	s = strings.Replace(s, "\")", "", -1)
	return s
}

//测试添加

//func Insert(){
//        defer close()
//        defer exption()
//        log.Println("****************************************")
//         var c =open("persion");
//        err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, &Person{"Cla", "+55 53 8402 8510"})
//        if err != nil {
//                panic(err)
//        }
//        result := Person{}
//        err = c.Find(bson.M{"name": "Ale"}).One(&result)
//        if err != nil {
//                panic(err)
//        }
//        log.Println("Phone:", result.Phone)
//        log.Println("********************end********************")
//}
